class OrderMade < ActiveRecord::Base  
  
  include DynamicDefaultScoping
  
  validates :enterprise_id, :presence => true
  validates :order_item_id,
    :presence => true
  validates :order_made_count,
    :numericality => {
      :greater_than_or_equal_to => 1
    }

  belongs_to :order_item
  belongs_to :updated_by_user, :class_name => 'User', :foreign_key => :updated_by_user_id
  belongs_to :feed
  has_many :feeds, :dependent => :destroy, :order => 'position asc'
  has_many :enters
  has_many :order_made_payments

  default_scope :current_enterprise,lambda {where(:enterprise_id => Enterprise.current_id )}
  scope :has_been_sent_to_factory, lambda{where('feeds.type = ? or feeds.type = ?','Feed::OrderMadeCreated','Feed::PaymentCreated').includes(:feed)}
  scope :has_been_payed_to_factory, lambda{where( 'feeds.type = ?','Feed::PaymentCreated').includes(:feed)}

  before_validation do |order_made|
#    order_made.enterprise_id ||= Enterprise.current_id
  end
  
  after_create do |order_made|
    Feed::OrderMadeCreated.create!(
      :order_item_id => order_made.order_item_id,
      :order_made_id => order_made.id)
  end

  before_save do |order_made|
    order_made.updated_by_user_id = User.current_id if order_made.changed?
  end

  after_save do |order_made|
    order_made.order_item.order.update_attribute(:order_made_on, order_made.order_made_on) if order_made.order_item.order.order_made_on.nil? or order_made.order_item.order.order_made_on < order_made.order_made_on
  end
  
  def reset_feed!
    update_attributes :feed_id => Feed.where(:order_made_id => id).last.try(:id)
  end

  def can_destroy?
    return false if enters.any? || order_made_payments.any?
    return true
  end
end
